<?php

namespace Tbf\Bundle\DatabaseBundle\ListQuery\ConditionalExpress;

use Doctrine\ORM\Query\Expr\Orx;
use Doctrine\ORM\QueryBuilder;

class AllLikeConditionalExpress extends AbstractConditionalExpress
{
    protected $value;
    public function __construct($value)
    {
        $this->value = $value;
    }
    //TODO: 哪些字段可以like???
    public function filterOrmQueryBuilder(QueryBuilder $qb)
    {
        $entities = $qb->getRootEntities();
        $first_entities = $entities[0];
        $class_metadata = $qb->getEntityManager()->getClassMetadata($first_entities);
        $like_field = array();
        foreach ($class_metadata->getFieldNames() as $field_name) {
            if (strpos(strtolower($field_name),'password')!==false) {
                continue;
            }
            if (!in_array($class_metadata->fieldMappings[$field_name]['type'],array('integer','string','text'))) {
                continue;
            }
            $like_field[] = $field_name;
        }
        $expr_list = array();
        foreach ($like_field as $field_name) {
            $expr_list[] = $qb->expr()->like(
                $this->handleFieldName($qb,$field_name),
                $this->placeHolderValue($qb,'%'.$this->value.'%'));
        }

        $qb->andWhere(new Orx($expr_list));

        /*
        foreach ($this->getExpressList() as $express_array) {
            $field = $this->handleFieldName($qb,$express_array['field']);
            $qb->andWhere($qb->expr()->like($field,
                $this->placeHolderValue($qb,'%'.$express_array['value'].'%')));
        }
        */
    }
}
